package qingxin.servlet.client.photo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.PhotoDAO;
import qingxin.factory.DAOFactory;
import qingxin.vo.Photo;

@WebServlet("/client/photo/getByAlbum")
public class PhotosServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private PhotoDAO photoDAO;

	public PhotosServlet(){
		super();
		photoDAO = DAOFactory.getPhotoDAO();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		try{
			int albumID = Integer.parseInt(request.getParameter("aid"));
			
			JSONObject jsonResult = new JSONObject();
			JSONArray jsonPhotos = new JSONArray();
			Photo[] photos = photoDAO.getByAlbumID(albumID);
			
			for(Photo photo : photos){
				JSONObject jsonPhoto = new JSONObject();
				jsonPhoto.put("original_addr", photo.getOriginalAddress());
				jsonPhoto.put("photographer", photo.getPhotographer());
				jsonPhoto.put("description", photo.getDescription());
				jsonPhotos.put(jsonPhoto);
			}
			
			jsonResult.put("photos", jsonPhotos);
			
			writer.println(jsonResult.toString());
			
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
